package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.ex.LoginException;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysUserService sysUserService;

    public String forward(String url){
        return UrlBasedViewResolver.FORWARD_URL_PREFIX+url;
    }
    public String redirect(String url){
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX+url;
    }
    @GetMapping("/login")
    public String toLogin(){
        return forward( "/login.jsp");
    }

    public HttpServletRequest request(){
//        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public HttpSession session(){
        return request().getSession();
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account, @RequestParam("password") String password){
        SysUser loginUser=sysUserService.login(account, password);
        if(loginUser!=null){
           session(Constants.SESSION_USER,loginUser);
            return "redirect:/main/index";
        }else {
            throw new LoginException("登录失败,用户名或密码错误");
        }
    }
    @GetMapping("/main/index")
    public String index(){
        return "index";
    }

//    @ExceptionHandler(value = RuntimeException.class)
//    public String handleException(RuntimeException e,HttpServletRequest request){
//        request.setAttribute(Constants.REQUEST_ERROR,e);
//
//        return "500";
//    }

    @GetMapping("/ex")
    public void throwException(){
        throw new RuntimeException("测试不同的异常到不同的页面");
    }

}
